package com.starbaba.mall.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.mall.service.MallItemTopicService;
import com.starbaba.mall.service.MallTopicService;
import com.starbaba.mall.service.ProductItemService;
import com.starbaba.mall.service.impl.MallItemTopicServiceImpl;
import com.starbaba.mall.service.impl.MallTopicServiceImpl;
import com.starbaba.mall.service.impl.ProductItemServiceImpl;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Item;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Item_Topic;
import com.tuanzi.server.loan_base.model.db.Loan_Mall_Topic;

/**
 * 天猫返利专题Action
 * @author chenweijun
 *
 */
@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class MallTopicAction extends BaseAction implements ModelDriven<Loan_Mall_Topic>{

	private Loan_Mall_Topic model;
	private MallTopicService topicService;
	private MallItemTopicService itemTopicService;
	private ProductItemService itemService;
	
	public MallTopicAction(){
		this.topicService = new MallTopicServiceImpl();
		this.itemTopicService = new MallItemTopicServiceImpl();
		this.itemService = new ProductItemServiceImpl();
	}
	
	
	@Override
	public Loan_Mall_Topic getModel() {
		if(model  == null){
			model = new Loan_Mall_Topic();
		}
		return model;
	}
	
	
	/**
	 * 查询专题列表
	 */
	public void getTopicList(){
		
		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		List<Loan_Mall_Topic> list = topicService.getTopicList(paramsMap, pageRequest.getIDisplayStart(),pageRequest.getIDisplayLength());
		int count=topicService.countTopic(paramsMap);
		pageResponse.setITotalDisplayRecords(count);
		pageResponse.setITotalRecords(count);
		try {
			pageResponse.setAaData(list);
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch(IOException e) {
			LogService.error(e);
		}
		
	}
	
	/**
	 * 打开新增或编辑专题页面
	 * @return
	 */
	public String showAddOrEditPage(){
		
		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		String id = (String) paramsMap.get("id");
		String source_ids = "";
		if(StringUtils.isNotEmpty(id)){
			 model = topicService.getTopic(Long.parseLong(id));
			 source_ids = itemTopicService.getSelectItemSourceIds(Long.parseLong(id));
		}
		
		paramsMap.put("model", model);
		paramsMap.put("source_ids", source_ids);
		
		return SUCCESS;
	}
	
	/**
	 * 保存专题
	 * @throws IOException
	 */
	public void saveTopic() throws IOException{
		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		paramsMap.put("img_file", model.getImg_file());
		paramsMap.put("small_img_file", model.getSmall_img_file());
		paramsMap.put("operator", getUserVO().getUsername());
		
		String id = (String) paramsMap.get("id");
		if(StringUtils.isEmpty(id)){ //新增
			topicService.addTopic(paramsMap);
		}else{//编辑
			topicService.updateTopic(paramsMap, Long.parseLong(id));
		}
		
		JsonObject response = new JsonObject();
		response.addProperty("result", "保存成功");
		sendJsonMessage(response.toString());
	}
	
	
	/**
	 * 上线、下线专题
	 */
	public String updateTopicStatus(){
		
		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		int result = topicService.updateTopicStatus(paramsMap);
		if(result > 0){
			return SUCCESS;
		}
		return ERROR;
		
	}
	
	/**
	 * 打开新增商品页面
	 */
	public String showProductPage(){
		
		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		String sourceIds = (String) paramsMap.get("sourceIds");
		
		paramsMap.put("sourceIds", sourceIds);
		
		return SUCCESS;
	}
	
	/**
	 * 查询全部在线商品
	 */
	public void getOnlineItemList(){
		
		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		List<Loan_Mall_Item> list = topicService.getOnlineItemList(paramsMap, pageRequest.getIDisplayStart(),pageRequest.getIDisplayLength());
		int count = topicService.countOnlineItem(paramsMap);
		
		try {
			pageResponse.setITotalDisplayRecords(count);
			pageResponse.setITotalRecords(count);
			pageResponse.setAaData(list);
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch(IOException e) {
			LogService.error(e);
		}
		
	}
	
	/**
	 * 查询商品
	 */
	public void getTopicItemList(){

		parsePageRequest();
		PageResponse pageResponse=new PageResponse();
		paramsMap=PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		String topic_id = (String)paramsMap.get("topic_id");
		String source_ids = (String)paramsMap.get("source_ids");
		
		List<Loan_Mall_Item_Topic> list = null;
		int count = 0;
		
		
		if(StringUtils.isNotEmpty(topic_id)){  //编辑主题，从关联表查	
			
			list = itemTopicService.getLoan_Mall_Item(Long.parseLong(topic_id), pageRequest.getIDisplayStart(),pageRequest.getIDisplayLength());
			count = itemTopicService.countLoan_Mall_Item(Long.parseLong(topic_id));
			
		}else{  //新增主题，从商品表查
			
			String source_id = "";
			if(StringUtils.isNotEmpty(source_ids)){
				
				String[] sourceIdArray = source_ids.split(",");
				for(int i=0; i < sourceIdArray.length; i++){
					if(StringUtils.isNotEmpty(sourceIdArray[i])){
						source_id = source_id + sourceIdArray[i];
						if(i != sourceIdArray.length - 1){
							source_id = source_id + ",";
						}
					}
				}    
				
			}
			              
			list = itemService.getLoan_Mall_ItemList(source_id);
			count = itemService.countLoan_Mall_ItemList(source_id);
		}
		
		try {
			pageResponse.setITotalDisplayRecords(count);
			pageResponse.setITotalRecords(count);
			pageResponse.setAaData(list);
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch(IOException e) {
			LogService.error(e);
		}
		
	}
	
	
	/**
	 * 排序
	 */
	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void sortTab() {
		parsePageRequest();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		topicService.sortTab(paramsMap);
		responseSuccess();
	
	}
	
	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

}
